#include "LevelConfig.h"
#include <string>
#include "GameConfig.h"
#include "Config.h"
#include "pugixml.hpp"
#include "ObjectDataDefine.h"

using namespace std;
using namespace pugi;

LevelConfig::LevelConfig(void)
{
	_listLevel = NULL;
}


LevelConfig::~LevelConfig(void)
{
	CC_SAFE_RELEASE(_listLevel);
}

LevelConfig* LevelConfig::sharedLevelConfig()
{
	if (!_instance)
		_instance = new	LevelConfig();
	return _instance;
}

void LevelConfig::loadConfig()
{
	setLevels(CCArray::create());
	//
	string data = string(dynamic_cast<CCString*>(GameConfig::sharedGameConfig()->getConfigData()->objectForKey(CONFIG_PLAYERLEVEL))->getCString());

	xml_document doc;
	xml_parse_result result = doc.load(data.c_str());
	//CCAssert(result.status == status_ok, "FAILD");

	xml_node node = doc.child("Root").child("LevelConfig");
	for (xml_node i = node.child("Level"); i; i = i.next_sibling("Level"))
	{
		int id = i.child("Id").text().as_int();
		int exp = i.child("Exp").text().as_int();

		LevelData* lvlData = new LevelData();
		lvlData->autorelease();
		lvlData->setId(id);
		lvlData->setEndExp(exp);

		_listLevel->addObject(lvlData);
	}
}

void LevelConfig::clearConfig()
{
	delete _instance;
	_instance = NULL;
}

int LevelConfig::getLevelByExp( int exp )
{
	for (int i = 0; i < _listLevel->count(); i++)
	{
		LevelData* lvlData = dynamic_cast<LevelData*>(_listLevel->objectAtIndex(i));
		if (exp < lvlData->getEndExp())
			return dynamic_cast<LevelData*>(_listLevel->objectAtIndex(i - 1))->getId();
	}
	return dynamic_cast<LevelData*>(_listLevel->lastObject())->getId();
}

LevelConfig* LevelConfig::_instance = NULL;
